/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.edu.ufcg.embedded.eolica.util;

import java.util.Vector;

/**
 * 
 * @author Maurilio
 */
public class TextUtils {
	/**
	 * Retorna um vetor de Strings a partir da string fornecida, separando os
	 * dados pelo caractere fornecido 'sep'
	 * 
	 * @param string
	 *            Contem os dados a serem extraidos
	 * @param sep
	 *            Separador dos dados
	 * @return ventor de inteiros
	 */
	public final static String[] spliti(String string, char sep) {
		int num = 0;
		string = string + sep;
		for (int i = 0; i < string.length(); i++) {
			if (string.charAt(i) == sep) {
				num++;
			}
		}
		String[] s = new String[num];
		int countS = 0;
		for (int i = 0; i < string.length(); i++) {
			if (string.charAt(i) == sep && string.charAt(i) != ' ') {
				try {
					s[countS] = string.substring(0, i).trim();
				} catch (NumberFormatException e) {
					e.printStackTrace();
				}
				string = string.substring(i + 1);
				countS++;
				i = 0;
			}
		}
		return s;
	}

	/**
	 * Retorna um vetor de Strings a partir da string fornecida, separando os
	 * dados por espaco
	 * 
	 * @param orig
	 * @param sep
	 * @return vetor de strings
	 */
	public static Vector split(String orig, char sep) {
		/**
		 * The file format is simple... each line in the file need be in the
		 * format: key = value \n
		 * 
		 * where: key = the key of the config value = the value of this key and
		 * 
		 * \n = new line
		 */
		char endln = '\n';
		orig = (orig).trim() + endln;

		Vector saida = new Vector();
		String key = "";
		String value = "";
		int pos = 0;

		for (int i = 0; i < orig.length(); i++) {
			if (orig.charAt(i) == sep) {
				// extract the key
				key = orig.substring(0, i - 1).trim();
				pos = i + 1;
			}
			if (orig.charAt(i) == endln) {
				// extract the value
				value = orig.substring(pos, i).trim();
				saida.addElement(new DataProperties(key, value));

				// reset the values
				orig = orig.substring(i + 1);
				i = 0;
				key = "";
				value = "";
				pos = 0;
			}
		}
		return saida;
	}

	/**
	 * Convert a string to number like: 12345.0 to 12345
	 * 
	 * @param string
	 *            the string to convert
	 * @return an integer
	 * @throws NumberFormatException
	 */
	public static int textToInt(String string) throws NumberFormatException {
		int s = string.length();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < s; i++) {
			if (string.charAt(i) == '.') {
				break;
			}
			sb.append(string.charAt(i));
		}
		return Integer.parseInt(sb.toString());
	}
}
